package com.custom.base.view

import android.content.Context
import android.util.AttributeSet
import android.widget.FrameLayout
import com.custom.base.R
import com.custom.base.util.SDViewUtil.screenHeight

/**
 * 作者：
 * 时间：2021/1/14
 * 描述：设置空间允许最高高度
 */
class SDMaxHeightView(context: Context, attrs: AttributeSet) : FrameLayout(context, attrs) {
    private var mMaxRatio = DEFAULT_MAX_RATIO // 优先级高
    private var mMaxHeight = DEFAULT_MAX_HEIGHT // 优先级低

    init {
        initAttrs(context, attrs)
        init()
    }

    private fun initAttrs(context: Context, attrs: AttributeSet) {
        val a = context.obtainStyledAttributes(
            attrs,
            R.styleable.MaxHeightView
        )
        val count = a.indexCount
        for (i in 0 until count) {
            val attr = a.getIndex(i)
            if (attr == R.styleable.MaxHeightView_SDHeightRatio) {
                mMaxRatio = a.getFloat(attr,
                    DEFAULT_MAX_RATIO
                )
            } else if (attr == R.styleable.MaxHeightView_SDHeightDimen) {
                mMaxHeight = a.getDimension(attr,
                    DEFAULT_MAX_HEIGHT
                )
            }
        }
        a.recycle()
    }

    private fun init() {
        mMaxHeight = if (mMaxHeight <= 0) {
            mMaxRatio * screenHeight.toFloat()
        } else {
            mMaxHeight.coerceAtMost(mMaxRatio * screenHeight.toFloat())
        }
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        val heightMode = MeasureSpec.getMode(heightMeasureSpec)
        var heightSize = MeasureSpec.getSize(heightMeasureSpec)
        if (heightMode == MeasureSpec.EXACTLY) {
            heightSize = if (heightSize <= mMaxHeight) heightSize else mMaxHeight.toInt()
        }
        if (heightMode == MeasureSpec.UNSPECIFIED) {
            heightSize = if (heightSize <= mMaxHeight) heightSize else mMaxHeight.toInt()
        }
        if (heightMode == MeasureSpec.AT_MOST) {
            heightSize = if (heightSize <= mMaxHeight) heightSize else mMaxHeight.toInt()
        }
        val maxHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
            heightSize,
            heightMode
        )
        super.onMeasure(widthMeasureSpec, maxHeightMeasureSpec)
    }

    companion object {
        private const val DEFAULT_MAX_RATIO = 0.6f
        private const val DEFAULT_MAX_HEIGHT = 0f
    }
}